package com.fast.fast.common.redis.config;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;

/**
 * Jedis配置类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@EnableCaching
@AutoConfiguration
public class JedisConfig {

    @Value("${spring.redis.host:127.0.0.1}")
    private String host;
    @Value("${spring.redis.port:6379}")
    private Integer port;
    private final String PASSWORD = "spring.redis.password";
    @Value("${spring.redis.lettuce.pool.min-idle:0}")
    private Integer minIdle;
    @Value("${spring.redis.lettuce.pool.max-idle:8}")
    private Integer maxIdle;
    @Value("${spring.redis.lettuce.pool.max-active:20}")
    private Integer maxTotal;
    @Value("${spring.redis.lettuce.pool.max-wait:-1}")
    private Integer maxWaitMillis;
    @Value("${spring.redis.lettuce.pool.shutdown-timeout:100}")
    private Integer evictorShutdownTimeoutMillis;

    @Autowired
    private Environment environment;

    @Bean
    public Jedis jedis() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);
        config.setMaxWait(Duration.ofMillis(maxWaitMillis));
        config.setEvictorShutdownTimeout(Duration.ofMillis(evictorShutdownTimeoutMillis));
        JedisPool jedisPool;
        String password = environment.getProperty(PASSWORD);
        if (ObjectUtil.isEmpty(password)) {
            jedisPool = new JedisPool(config, host, port, 0);
        } else {
            jedisPool = new JedisPool(config, host, port, 0, password);
        }
        return jedisPool.getResource();
    }


}
